package tema10.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.annotation.WebServlet;
import javax.servlet.ServletContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tema10.persistence.ContactoDAO;
import tema10.persistence.ContactoPersistFactory;

@WebServlet(name="PersistenceConfigChooseServlet", urlPatterns={"/tema10/agendaConfigJDBC","/tema10/agendaConfigPool"})
public class PersistenceConfigChooseServlet extends HttpServlet {
    
    private final String dirMenuAgendaCRUD = "/tema10/menuAgendaCRUD.html";
    private final String dirJDBCConfig = "/EjemploBasicoJavaEE/tema10/agendaConfigJDBC";
    private final String dirPoolConfig = "/EjemploBasicoJavaEE/tema10/agendaConfigPool";
    private ContactoDAO contactoDAO;
    
    @Override
    public void init() {
        ServletConfig config = getServletConfig();
        ServletContext context = config.getServletContext();
        context.setAttribute("persistenceMechanism", context.getInitParameter("persistenceMechanism"));
        connect();
    }

    @Override
    public void destroy() {
        disconnect();
    }
    
    protected void connect() {
        String url, driver, user, password, persistenceMechanism;
        ServletConfig config = getServletConfig();
        ServletContext context = config.getServletContext();
        String connectionFileName = context.getInitParameter("connectionConfigFile");
        InputStream is = context.getResourceAsStream(connectionFileName);
        Properties connectionFile = new Properties();
        try {
            connectionFile.load(is);
        } catch (IOException ex) {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.SEVERE,
                    "Error cargando los parametros del fichero de configuracion de BD", ex);
            //En este caso sacamos los parametros del contexto
            url = context.getInitParameter("databaseURL");
            driver = context.getInitParameter("databaseDriver");
            user = context.getInitParameter("databaseUser");
            password = context.getInitParameter("databasePassword");
        }
        url = connectionFile.getProperty("url");
        driver = connectionFile.getProperty("driver");
        user = connectionFile.getProperty("user");
        password = connectionFile.getProperty("password");
        persistenceMechanism = (String) context.getAttribute("persistenceMechanism");
        
        Logger.getLogger(StartUpListener.class.getName()).log(Level.INFO, 
                "Estableciendo conexion con la BD empleando: {0}...", persistenceMechanism);
        contactoDAO = ContactoPersistFactory.getContactoDAO(persistenceMechanism);
        boolean connected = contactoDAO.setUp(url, driver, user, password);
        if (!connected) {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.INFO, 
                "Error conectando a la BD");
            context.setAttribute("persistenceMechanism", "none");
        } else {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.INFO, 
                "Conexion con la BD realizada con exito");
        }
    }
    
    protected void disconnect() {
        boolean disconnected = contactoDAO.disconnect();
        if (!disconnected) {
            Logger.getLogger(StartUpListener.class.getName()).log(Level.SEVERE,
                    "No se encontro el driver para la base de datos");
        }
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String persistConfig = request.getRequestURI();
        ServletContext context = request.getServletContext();
        String persistenceMechanism = (String) context.getAttribute("persistenceMechanism");
        Boolean persistenceChanged = false;
        if(persistConfig.equals(dirJDBCConfig)) {
            if(!persistenceMechanism.equals("jdbc")){
                persistenceChanged = true;
                context.setAttribute("persistenceMechanism", "jdbc");
                Logger.getLogger(PersistenceConfigChooseServlet.class.getName()).log(Level.INFO,
                    "Actualizada configuracion persistencia a JDBC");
            }   
        } else if(persistConfig.equals(dirPoolConfig)) {
            if(!persistenceMechanism.equals("pool")){
                persistenceChanged = true;
                context.setAttribute("persistenceMechanism", "pool");
                Logger.getLogger(PersistenceConfigChooseServlet.class.getName()).log(Level.INFO,
                    "Actualizada configuracion persistencia a Pool");
            }            
        } else {
            context.setAttribute("persistenceMechanism", "none");
            gotoURL("/tema8/404error.html",request,response);
        }
        if (persistenceChanged) {
            disconnect();
            persistenceMechanism = (String) context.getAttribute("persistenceMechanism");
            Logger.getLogger(StartUpListener.class.getName()).log(Level.INFO, 
                "RECONECTANDO con la BD empleando: {0}...", persistenceMechanism);
            connect();
        }        
        gotoURL(dirMenuAgendaCRUD,request,response);
    }

    protected void gotoURL(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }
    
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
}